<?php

namespace app\admin\controller\wdsxh;

use app\admin\model\wdsxh\Order;
use app\common\controller\Backend;
use Exception;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\cache\driver\Redis;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 会员风采
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\wdsxh\Member
     */
    protected $model = null;


    private $adminInfo;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wdsxh\Member;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("indexList", $this->model->getIndexList());

        $adminInfo = $this->auth->getUserInfo();
        $group_id = $this->auth->getGroupIds()[0];
        $adminInfo['group_id'] = $group_id;
        $this->adminInfo = $adminInfo;
        $this->assignconfig('adminInfo',$adminInfo);

//        $redis = redis()->handler();
        $redis = (new Redis(config('queue')))->handler();
        $count = $redis->llen('queues:hzsxysh');
        $this->assignconfig('redislist',$count);
        $this->view->assign('redislist',$count);
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $adminInfo = $this->adminInfo;
            if($adminInfo['group_id'] == 4){
                $this->model->where('commerce_id',$adminInfo['commerce_id']);
            }

            $list = $this->model
                ->where($where)
                ->where('status','>=','0')
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row){
                $row->level;
                $row->company;
                $row->commerce;
            }

            $redis = (new Redis(config('queue')))->handler();
            $count = $redis->llen('queues:hzsxysh');

            $result = array("total" => $list->total(), "rows" => $list->items(),"extend" => ['count' => $count]);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function seluser(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $user=new \app\admin\model\User();
            $list = $user
                ->where('nickname','neq','')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $company = $params['company'];
                unset($params['company']);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    /*修改企业信息*/
                    (new \app\admin\model\wdsxh\MemberUnit())->where(['member_id' => $ids,'status' => '1'])->update($company);

                    // 未创建入会申请信息bug处理,
                    // 判断是否有入会申请信息
                    // 添加入会申请数据
                    $MemberProfile = (new \app\admin\model\wdsxh\MemberProfile())->get(['uid' => $row['uid']]);
                    if(!$MemberProfile){
                        (new \app\admin\model\wdsxh\MemberProfile())->create([
                            'uid' => $row['uid'],
                            'name' => $row['name'],
                            'mobile' => $row['mobile'],
                            'status' => '1',
                            'createtime' => time(),
                        ]);
                    }

                    Db::commit();
                } catch (ValidateException | Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row->user;
        $row->company;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            $param['status'] = 3;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    \app\admin\model\wdsxh\MemberProfile::where('uid',$v->uid)->delete();
                    \app\admin\model\wdsxh\Business::where('uid',$v->id)->update($param);
                    \app\admin\model\wdsxh\MemberUnit::where('member_id',$v->id)->delete();
                    \app\admin\model\wdsxh\MemberVisitor::where('member_id',$v->id)->delete();
                    \app\admin\model\wdsxh\Order::where('uid',$v->uid)->where('type',2)->where('status','in',['2','5'])->delete();
                    \app\admin\model\wdsxh\ActivityRefund::where('member_id',$v->id)->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $company = $params['company'];
                unset($params['company']);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    /*创建用户*/
                    // 如果未选中用户,则新建一个
                    if(empty($params['uid'])) {
                        if(!preg_match("/^1[3456789]\d{9}$/", $params['mobile'])){
                            Exception('手机号格式错误');
                        }
                        (new \app\common\library\Auth)->register($params['mobile'],'123456','',$params['mobile']);
                        $user = model('app\common\model\User')->get(['mobile' => $params['mobile']]);
                        $params['uid'] = $user->id;
                    }
                    /*创建用户*/

                    $create_member_profile_data = [
                        'uid' => $params['uid'],
                        'name' => $params['name'],
                        'mobile' => $params['mobile'],
                        'status' => '1',
                        'createtime' => time(),
                    ];
                    $params['status'] = '1';
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->create($params);

                    /*创建企业*/
                    $company['level_id'] = $params['level_id'];
                    $company['member_id'] = $result->id;
                    (new \app\admin\model\wdsxh\MemberUnit())->create($company);
                    /*创建企业*/

                    (new \app\admin\model\wdsxh\MemberProfile())->allowField(true)->save($create_member_profile_data);
                    $money = (new \app\admin\model\wdsxh\MemberUnitLevel())->where('id',$params['level_id'])->value('expense');
                    $orderData=array(
                        'uid' => $params['uid'],
                        'items_id' => $result->id,
                        'type' => 2,
                        'order_sn' => wdsxh_create_order(),
                        'money' => $money,
                        'status' => '5',
                        'createtime' => time(),
                        'paytime' => time(),
                    );
                    Order::create($orderData);
                    Db::commit();
                } catch (ValidateException | PDOException | Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage(),'',$e->getLine());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->where('status','>=','0')->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->where('status','>=','0')
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 导入
     */
    public function import()
    {
        set_time_limit(0);
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fieldArr = [
            '会员姓名' => 'name',
            '性别' => 'gender',
            '联系电话' => 'mobile',
            '会员籍贯' => 'birthplace',
            '政治面貌' => 'political_status',
//            '所属商会' => 'commerce_id',
            '商会职务' => 'level_id',
            '单位职务' => 'company_post',
            '会员简介' => 'introduction',
            '行业分类' => 'cat_id',
            '公司名称' => 'company_name',
            '公司介绍' => 'company_introduce',
            '公司电话' => 'company_mobile',
            '公司地址' => 'company_address',
        ];

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, 1)->getValue();
                $fields[] = $val;
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : (is_object($val) ? $val->__toString() : $val);
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                    // 队列异步处理
                    Queue('app\common\job\Member@importMember',$row,0,'hzsxysh');
//                    \think\Queue::later($currentRow, 'app\common\job\Member@importMember', $row, 'hzsxysh');
                }
            }
//            if (!$insert) {
//                $this->error(__('No rows were updated'));
//            }
//            $this->model->insertAll($insert);
        } catch (Exception $exception) {
            $this->error($exception->getMessage(),'',$exception->getLine());
        }

        $this->success('已加入处理队列','',$insert);
    }

}
